<template>
	<div v-loading="loading" class="page_table">
		<!-- 操作按钮 -->
		<div v-if="showToolbar" class="toolbar">
			<slot name="toolbar"> </slot>
		</div>

		<!-- table表格 -->
		<el-table :data="data" :border="border" :height="height" v-bind="childrenProps">
			<el-table-column v-if="showIndexColumn" label="序号" type="index" width="55" align="center" />
			<template v-for="propItem in propList" :key="propItem.prop">
				<el-table-column v-bind="propItem" :align="propItem.align ?? 'center'">
					<template #default="{ row }">
						<slot :name="propItem.slotName" :row="row">
							{{ row[propItem.prop] }}
						</slot>
					</template>
				</el-table-column>
			</template>
		</el-table>

		<!-- 分页 -->
		<div v-if="total > 0" class="footer">
			<slot name="footer">
				<el-pagination
					background
					layout="total, prev, pager, next, jumper"
					:total="total"
					:page-size="page.pageSize"
					:current-page="page.pageNum"
					@current-change="onCurrentChange"
				>
				</el-pagination>
			</slot>
		</div>
	</div>
</template>

<script name="ContentTable" setup lang="ts">
import { ref, watch, useSlots, withDefaults } from 'vue'

const props = withDefaults(
	defineProps<{
		data: any
		propList: any
		showIndexColumn?: boolean
		total?: number
		page?: { pageNum: number; pageSize: number }
		pageChange?: any
		childrenProps?: any
		border?: boolean
		height?: string | number | null
		padding?: string
	}>(),
	{
		data: [],
		propList: [],
		showIndexColumn: false,
		total: 0,
		page: () => ({ pageNum: 0, pageSize: 10 }),
		pageChange: () => ({}),
		childrenProps: () => ({}),
		border: false,
		height: null,
		padding: '15px'
	}
)

const showToolbar = ref(false)
const slots = useSlots()
// 判断toolbar插槽有没有插入元素
if (slots.toolbar) {
	showToolbar.value = true
}

const loading = ref(true)
watch(
	() => props.data,
	() => {
		loading.value = false
	}
)
if (props.data.length) {
	loading.value = false
}

const emit = defineEmits(['update:page'])
function onCurrentChange(pageNum: number) {
	loading.value = true
	emit('update:page', {
		pageNum: pageNum,
		pageSize: props.page.pageSize
	})
	props.pageChange()
}

defineExpose({
	loading
})
</script>

<style lang="less" scoped>
.page_table {
	background: #fff;
	padding: v-bind(padding);
	border-radius: 5px;
}
.toolbar {
	margin-bottom: 15px;
}
.footer {
	margin-top: 20px;
	display: flex;
	justify-content: flex-end;
}
:deep(.el-table th.el-table__cell) {
	background: #f1f3f4;
	color: #3c3c3c;
}
</style>
